package cn.com.lyj6851.modules.shop.controller;


import cn.com.lyj6851.constant.ShopConstants;
import cn.com.lyj6851.exception.BadRequestException;
import cn.com.lyj6851.logging.aop.AopLog;
import cn.com.lyj6851.modules.shop.domain.YdySystemGroupData;
import cn.com.lyj6851.modules.shop.service.YdySystemGroupDataService;
import cn.com.lyj6851.modules.shop.service.dto.YdySystemGroupDataQueryCriteria;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;


@Api(tags = "商城:数据配置管理")
@RestController
@RequestMapping("api")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class SystemGroupDataController {

    private final YdySystemGroupDataService systemGroupDataService;

    @AopLog("查询数据配置")
    @ApiOperation(value = "查询数据配置")
    @GetMapping(value = "/ydySystemGroupData")
    @PreAuthorize("hasAnyRole('admin','SYSTEMGROUPDATA_ALL','SYSTEMGROUPDATA_SELECT')")
    public ResponseEntity getYdySystemGroupDatas(YdySystemGroupDataQueryCriteria criteria, Pageable pageable){
        Sort sort = Sort.by(Sort.Direction.DESC,"sort");
        Pageable pageableT = PageRequest.of(pageable.getPageNumber(),
                pageable.getPageSize(),
                sort);
        return new ResponseEntity<>(systemGroupDataService.queryAll(criteria,pageable), HttpStatus.OK);
    }

    @AopLog("修改数据配置")
    @ApiOperation(value = "修改数据配置")
    @PutMapping(value = "/ydySystemGroupData")
    @CacheEvict(cacheNames = ShopConstants.LYJ_SHOP_REDIS_INDEX_KEY,allEntries = true)
    @PreAuthorize("hasAnyRole('admin','SYSTEMGROUPDATA_ALL','SYSTEMGROUPDATA_EDIT')")
    public ResponseEntity update(@RequestBody String jsonStr) {
        JSONObject jsonObject = JSON.parseObject(jsonStr);
        this.checkParam(jsonObject);
        YdySystemGroupData systemGroupData = new YdySystemGroupData();
        systemGroupData.setGroupName(jsonObject.get("groupName").toString());
        jsonObject.remove("groupName");
        systemGroupData.setValue(jsonObject.toJSONString());
        if(jsonObject.getInteger("status") == null){
            systemGroupData.setStatus(1);
        }else {
            systemGroupData.setStatus(jsonObject.getInteger("status"));
        }
        if(jsonObject.getInteger("sort")==null){
            systemGroupData.setSort(0);
        }else {
            systemGroupData.setSort(jsonObject.getInteger("sort"));
        }
        systemGroupData.setId(Integer.valueOf(jsonObject.get("id").toString()));
        systemGroupDataService.saveOrUpdate(systemGroupData);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @AopLog("新增数据配置")
    @ApiOperation(value = "新增数据配置")
    @PostMapping(value = "/ydySystemGroupData")
    @CacheEvict(cacheNames = ShopConstants.LYJ_SHOP_REDIS_INDEX_KEY,allEntries = true)
    @PreAuthorize("hasAnyRole('admin','SYSTEMGROUPDATA_ALL','SYSTEMGROUPDATA_CREATE')")
    public ResponseEntity create(@RequestBody String jsonStr){
        JSONObject jsonObject = JSON.parseObject(jsonStr);
        this.checkParam(jsonObject);

        YdySystemGroupData ydySystemGroupData = new YdySystemGroupData();
        ydySystemGroupData.setGroupName(jsonObject.get("groupName").toString());
        jsonObject.remove("groupName");
        ydySystemGroupData.setValue(jsonObject.toJSONString());
        ydySystemGroupData.setStatus(jsonObject.getInteger("status"));
        ydySystemGroupData.setSort(jsonObject.getInteger("sort"));

        return new ResponseEntity<>(systemGroupDataService.save(ydySystemGroupData),HttpStatus.CREATED);
    }

    @AopLog("删除数据配置")
    @ApiOperation(value = "删除数据配置")
    @DeleteMapping(value = "/ydySystemGroupData/{id}")
    @PreAuthorize("hasAnyRole('admin','SYSTEMGROUPDATA_ALL','SYSTEMGROUPDATA_DELETE')")
    public ResponseEntity delete(@PathVariable Integer id){
        systemGroupDataService.removeById(id);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * 检测参数
     * @param jsonObject /
     */
    private void checkParam(JSONObject jsonObject){
        if(ObjectUtil.isNotNull(jsonObject.get("name"))){
            if(StrUtil.isEmpty(jsonObject.getString("name"))){
                throw new BadRequestException("名称必须填写");
            }
        }
        if(ObjectUtil.isNotNull(jsonObject.get("title"))){
            if(StrUtil.isEmpty(jsonObject.getString("title"))){
                throw new BadRequestException("标题必须填写");
            }
        }
        if(ObjectUtil.isNotNull(jsonObject.get("pic"))){
            if(StrUtil.isEmpty(jsonObject.getString("pic"))){
                throw new BadRequestException("图片必须上传");
            }
        }
        if(ObjectUtil.isNotNull(jsonObject.get("info"))){
            if(StrUtil.isEmpty(jsonObject.getString("info"))){
                throw new BadRequestException("简介必须填写");
            }
        }
    }

}
